package impl

import (
	"fmt"
	"io"
	"net/http"

	"gitee.com/jabberwocky238/proj-backend/model"
	"gitee.com/jabberwocky238/proj-backend/util"
)

func SyncUserPlaylist(uploaderUuid string, playlistId string) error {
	playlist := _Playlist{playlistID: playlistId}
	return playlist.load(uploaderUuid)
}

type _Music struct {
	name     string
	artist   string
	coverUrl string
	uploader string
	blobUrl  string
}

// interface model.IntoMusicORM
func (o *_Music) Name() string {
	return o.name
}
func (o *_Music) Artist() string {
	return o.artist
}
func (o *_Music) Uploader() string {
	return o.uploader
}
func (o *_Music) CoverUrl() string {
	return o.coverUrl
}

func (o *_Music) save() error {
	// check if music already exists
	exists, err := model.Exists(o)
	if err != nil {
		fmt.Println("Error:", err)
		return err
	}
	if exists {
		return nil
	}
	// generate ORM obj
	ormObj := model.IntoMusic(o)
	// emit download task
	err1 := emitDownloadTask(ormObj.UUID, o.blobUrl)
	if err1 != nil {
		fmt.Println("Error:", err)
		return err
	}
	// save music to db
	return util.DB.Create(&ormObj).Error
}

type _Playlist struct {
	playlistID string
}

func (o *_Playlist) load(uploaderUuid string) error {
	// get all musics
	musics, err := getAllMusicFromPlaylist(o.playlistID, uploaderUuid)
	if err != nil {
		fmt.Println("Error:", err)
		return err
	}
	// respectively download music and add it to db
	for _, music := range musics {
		go music.save()
	}
	return nil
}

func getAllMusicFromPlaylist(playlist_id string, uploaderUuid string) ([]_Music, error) {
	// get uploader cookie
	// uploaderCookie, err := getUploaderCookie(uploaderUuid)
	// if err != nil {
	// 	fmt.Println("Error:", err)
	// 	return err
	// }
	// get playlist content
	panic("unimplemented")
}

func getUploaderCookie(uploaderUuid string) (any, error) {
	panic("unimplemented")
}

func emitDownloadTask(uuid, url string) error {
	// 发送至存储节点
	requestBase := "http://127.0.0.1:30001"
	requestUrl := fmt.Sprintf("%s/download/v1?uuid=%s&url=%s", requestBase, uuid, url)
	resp, err := http.Get(requestUrl)
	if err != nil {
		fmt.Println("Error:", err)
		return err
	}
	defer resp.Body.Close()
	return nil
}

func getMusicUrl(music_id string) (string, error) {
	// 发送 GET 请求
	requestBase := "http://127.0.0.1:20000"
	requestUrl := requestBase + "/song/url/v1?id=" + music_id + "&level=exhigh"
	resp, err := http.Get(requestUrl)
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}
	return string(body), nil
}
